package me.pearjelly.task.impl;

import me.pearjelly.exception.PicExistException;
import me.pearjelly.exception.ProcessPicFailException;
import me.pearjelly.model.Image;
import me.pearjelly.model.Pic;
import me.pearjelly.service.ImageService;
import me.pearjelly.service.ProcessPicService;
import me.pearjelly.task.PageTask;
import me.pearjelly.util.ImageQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import edu.uci.ics.crawler4j.crawler.CrawlController;

@Component
public class ProcessPicTask implements PageTask {

	@Override
	public void run() {
		while (this.running) {
			try {
				Image image = ImageQueue.poll();
				if (null != image) {
					try {
						logger.info("Begin process image:{}", image);
						Pic pic = processPicService.addPic(image);
						imageService.convertImage(pic, image.getPageContext()
								.getBinaryData());
					} catch (ProcessPicFailException e) {
						logger.warn("Process image:{}, error:{}", image,
								e.getMessage());
						ImageQueue.offer(image);
					} catch (PicExistException e) {
						logger.warn("Process existed image:{}", image);
					}
				}
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private static final Logger logger = LoggerFactory
			.getLogger(ProcessPicTask.class);
	@SuppressWarnings("unused")
	private CrawlController controller;
	private boolean running = true;
	private ProcessPicService processPicService;
	private ImageService imageService;

	@Autowired
	public void setProcessPicService(ProcessPicService processPicService) {
		this.processPicService = processPicService;
	}

	@Autowired
	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	@Override
	public void destory() {
		this.running = false;
	}

	@Override
	public void setController(CrawlController crawlController) {
		this.controller = crawlController;
	}
}
